<template>
  <!-- 培训班多时段安排区域 -->
  <div class="training-sessions">
    <!-- 顶部基础信息 + 学员通知按钮 -->
    <div class="session-header">
      <span class="info-item">培训班编号：{{ trainingClassCode || '-' }}</span>
      <span class="info-item">培训班名称：{{ className || '-' }}</span>
      <span class="info-item" v-if="handoverStatus">状态：<span :class="statusClass">{{ statusText }}</span></span>
      <el-button
        type="primary"
        @click="handleStudentNotice"
        :loading="noticeLoading"
      >
        学员通知
      </el-button>
    </div>

    <!-- 循环渲染每个"培训内容"分组 -->
    <div
      v-for="(session, index) in trainingSessions"
      :key="index"
      class="session-group"
      :class="{ 'session-group-disabled': handoverStatus === 'completed' }"
    >
      <!-- 培训内容 + 上传操作区 -->
      <div class="session-content-header">
        <span class="content-label">培训内容</span>
        <span class="content-value">{{ session.trainingContent || '-' }}</span>

        <!-- <div class="upload-area">
          <span class="upload-label">上传安排名单</span>
          <el-upload
            :disabled="handoverStatus === 'completed'"
            class="upload-btn"
            action="/api/upload"
            :show-file-list="false"
            :on-success="(response) => handleUploadSuccess(response, index)"
            :on-error="handleUploadError"
            :loading="session.uploadLoading"
            accept=".xlsx,.xls"
          >
            <el-button type="primary" size="mini">{{ session.uploadBtnText }}</el-button>
          </el-upload>
        </div> -->
      </div>

      <!-- 时段安排表格 -->
      <el-table
        :data="session.arrangeList"
        border
        style="width: 100%; margin-top: 10px;"
        :empty-text="session.arrangeList.length === 0 ? '暂无时段安排，可上传名单或手动添加' : '加载中...'"
      >
        <el-table-column prop="startTime" label="开始时间" width="160"></el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="160"></el-table-column>
        <el-table-column prop="address" label="培训地址"></el-table-column>
        <!-- 动态判断"预约人数"/"安排人数" -->
        <el-table-column
          :prop="getPeopleCountProp(session)"
          :label="getPeopleCountLabel(session)"
          width="120"
        ></el-table-column>
        <el-table-column prop="peopleLimit" label="人数限制" width="120"></el-table-column>
        <el-table-column prop="teacher" label="培训教师"></el-table-column>
        <el-table-column prop="description" label="说明"></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button
              type="text"
              @click="handleViewList(scope.row, session.operationText)"
              :disabled="!scope.row.id"
            >
              {{ session.operationText }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 学员通知弹窗 -->
    <el-dialog
      title="发送学员通知"
      :visible.sync="noticeDialogVisible"
      width="50%"
      :before-close="handleNoticeDialogClose"
    >
      <el-form :model="noticeForm" ref="noticeForm" :rules="noticeRules">
        <el-form-item label="通知类型" prop="sendTypes">
          <el-checkbox-group v-model="noticeForm.sendTypes">
            <el-checkbox label="0">短信</el-checkbox>
            <el-checkbox label="1">门户</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="通知内容" prop="content">
          <el-input
            type="textarea"
            v-model="noticeForm.content"
            placeholder="请输入通知内容"
            rows="6"
          ></el-input>
        </el-form-item>
        <el-form-item label="发送范围">
          <el-radio-group v-model="noticeForm.range" @change="handleRangeChange">
            <el-radio label="all">所有学员</el-radio>
            <el-radio label="selected">指定学员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="noticeForm.range === 'selected'"
          class="selected-users-form-item"
          prop="selectedUsers"
          :rules="[{ required: true, message: '请至少选择一个学员', trigger: 'change' }]"
        >
          <el-select
            v-model="noticeForm.selectedUsers"
            multiple
            placeholder="请输入学员姓名搜索并选择"
            filterable
            remote
            :remote-method="queryUsers"
            :loading="userLoading"
            style="width: 100%;"
            clearable
            @clear="handleSelectClear"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.studentId"
              :label="user.studentName"
              :value="user.studentId"
            >
              <span style="float: left">{{ user.studentName }}</span>
              <!-- <span style="float: right; color: #8492a6; font-size: 13px">
                {{ user.projectName }}
              </span> -->
              <span style="float: right; color: #8492a6; font-size: 13px">
                身份证号：{{ user.idCard || '无证件号' }}
              </span>
            </el-option>
            <template #empty>
              <div style="text-align: center; color: #909399;">
                {{ userLoading ? '搜索中...' : '无匹配学员，请更换关键词' }}
              </div>
            </template>
          </el-select>
          <div class="selected-count" v-if="noticeForm.range === 'selected'">
            已选择 {{ noticeForm.selectedUsers.length }} 名学员
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="noticeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitNotice" :loading="noticeLoading">发送</el-button>
      </div>
    </el-dialog>

    <!-- 预约名单弹窗 -->
    <el-dialog
      :title="reservationDialogTitle"
      :visible.sync="reservationDialogVisible"
      width="1200px"
      height="800px"
      class="reservation-dialog"
    >
      <div class="reservation-info">
        <div class="info-row">
          <span class="info-label">培训班编号：</span>
          <span class="info-value">{{ trainingClassCode || '-' }}</span>
          <span class="info-label">培训班名称：</span>
          <span class="info-value">{{ reservationInfo.className || '-' }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">培训内容：</span>
          <span class="info-value">{{ reservationInfo.trainingContent || '-' }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">开始时间：</span>
          <span class="info-value">{{ reservationInfo.startTime || '-' }}</span>
          <span class="info-label">结束时间：</span>
          <span class="info-value">{{ reservationInfo.endTime || '-' }}</span>
          <span class="info-label">培训地址：</span>
          <span class="info-value">{{ reservationInfo.address || '-' }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">人数限制：</span>
          <span class="info-value">{{ reservationInfo.peopleLimit || '-' }}</span>
          <span class="info-label">当前预约人数：</span>
          <span class="info-value">{{ reservedStudents.length }}</span>
          <span class="info-label" v-if="reservationInfo.peopleLimit">剩余名额：</span>
          <span class="info-value" v-if="reservationInfo.peopleLimit" :class="remainingQuotaClass">
            {{ Math.max(0, reservationInfo.peopleLimit - reservedStudents.length) }}
          </span>
        </div>
      </div>

      <div class="students-container">
        <div class="students-panel">
          <div class="panel-header">
            <h3 class="panel-title">预约学员</h3>
            <el-button
              type="text"
              @click="batchRemoveReservation"
              class="batch-btn"
              :disabled="!selectedReservedStudents.length"
            >
              批量移出
            </el-button>
          </div>
          <el-table
            ref="reservedTable"
            :data="reservedStudents"
            border
            style="width: 100%;"
            @selection-change="handleReservedSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="name" label="姓名" width="150"></el-table-column>
            <el-table-column prop="projectName" label="项目" width="200"></el-table-column>
            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button
                  type="text"
                  @click="handleRemoveReservation(scope.row)"
                >
                  移出
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="students-panel">
          <div class="panel-header">
            <h3 class="panel-title">未预约学员</h3>
            <el-button
              type="text"
              @click="batchAddReservation"
              class="batch-btn"
              :disabled="!selectedUnreservedStudents.length || (reservationInfo.peopleLimit && reservedStudents.length >= reservationInfo.peopleLimit)"
            >
              批量预约
            </el-button>
          </div>
          <el-table
            ref="unreservedTable"
            :data="unreservedStudents"
            border
            style="width: 100%;"
            @selection-change="handleUnreservedSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="name" label="姓名" width="150"></el-table-column>
            <el-table-column prop="projectName" label="项目" width="200"></el-table-column>
            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button
                  type="text"
                  @click="handleAddReservation(scope.row)"
                  :disabled="reservationInfo.peopleLimit && reservedStudents.length >= reservationInfo.peopleLimit"
                >
                  预约
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { selectListByClassId } from '@/api/training/practiceAppointment.js';
import { getClassStudents } from "@/api/training/ClassStudent";
import { selectClassStudentAppointmentStatus, editAppointmentStatus, addPractice } from '@/api/training/practiceClassStudent.js';
import { studentNoticeProcess } from "@/api/training/studentNotice.js";

export default {
  name: 'TrainingClassPage',
  data() {
    return {
      // 培训班基本信息
      classId: '',
      className: '',
      handoverStatus: '',
      trainingClassCode: '',

      // 培训时段数据（默认初始化一个空结构，确保页面框架渲染）
      trainingSessions: [{
        trainingContent: "无",
        arrangeList: [],
        uploadBtnText: "上传安排名单",
        operationText: "查看预约名单",
        uploadLoading: false,
        loading: false
      }],

      // 学员通知相关
      noticeDialogVisible: false,
      noticeLoading: false,
      noticeForm: {
        content: '',
        range: 'all',
        selectedUsers: [],
        sendTypes: []
      },
      noticeRules: {
        range: [
          { required: true, message: '请选择发送途径', trigger: 'blur' }
        ],
        sendTypes: [
          { required: true, message: '请选择通知类型', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入通知内容', trigger: 'blur' },
          { max: 500, message: '内容不能超过500个字符', trigger: 'blur' }
        ]
      },

      // 用户选择相关
      userOptions: [],
      allUsers: [],
      userLoading: false,

      // 预约名单弹窗相关
      reservationDialogVisible: false,
      reservationDialogTitle: "查看预约名单",
      reservationInfo: {},
      reservedStudents: [],
      unreservedStudents: [],
      selectedReservedStudents: [],
      selectedUnreservedStudents: [],

      currentScheduleId: ''
    };
  },
  computed: {
    statusText() {
      const statusMap = {
        'draft': '草稿',
        'ongoing': '进行中',
        'completed': '已完成'
      };
      return statusMap[this.handoverStatus] || this.handoverStatus;
    },
    statusClass() {
      const classMap = {
        'draft': 'status-draft',
        'ongoing': 'status-ongoing',
        'completed': 'status-completed'
      };
      return classMap[this.handoverStatus] || '';
    },
    remainingQuotaClass() {
      const remaining = this.reservationInfo.peopleLimit - this.reservedStudents.length;
      return remaining <= 0 ? 'remaining-quota-warning' : '';
    }
  },
  watch: {
    noticeDialogVisible(newVal) {
      if (newVal) {
        this.initNoticeForm();
      }
    },
    '$route.query.classId': {
      immediate: true,
      handler(newId) {
        const params = this.$route.params;
        this.classId = params.classId || newId; // 兼容params和query传参
        this.className = params.className;
        this.handoverStatus = params.handoverStatus;
        this.trainingClassCode = params.trainingClassCode;
        this.loadTrainingData(); // 确保路由参数变化后重新加载数据
      }
    }
  },
  created() {
    this.loadTrainingData();
  },
  methods: {
    initNoticeForm() {
      this.noticeForm = {
        content: '',
        range: 'all',
        selectedUsers: [],
        sendTypes: []
      };

      if (this.allUsers.length > 0) {
        this.setAllStudents();
      } else {
        this.loadStudentsData();
      }

      this.$nextTick(() => {
        if (this.$refs.noticeForm) {
          this.$refs.noticeForm.clearValidate();
        }
      });
    },

    async loadStudentsData() {
      try {
        const res = await getClassStudents({
          trainingClassId: this.classId,
        });

        this.allUsers = res.rows.map(item => {
          const registration = item.registrationDto || {};
          return {
            studentId: registration.studentId || item.studentId,
            studentName: registration.studentName || item.studentName,
            projectName: registration.projectMap || item.projectName || '-', // 适配后端projectMap字段
            idCard: registration.idNumber || item.idNumber,
          };
        }).filter(user => user.studentId && user.studentName);

        this.userOptions = [...this.allUsers];

        if (this.noticeForm.range === 'all') {
          this.setAllStudents();
        }
      } catch (error) {
        console.error("加载学员数据失败：", error);
        this.$message.error("加载学员数据失败");
      }
    },

    handleRangeChange(newRange) {
      if (newRange === 'all') {
        this.setAllStudents();
      } else if (newRange === 'selected') {
        this.noticeForm.selectedUsers = [];
      }

      this.$nextTick(() => {
        if (this.$refs.noticeForm) {
          this.$refs.noticeForm.clearValidate('selectedUsers');
        }
      });
    },

    setAllStudents() {
      if (this.allUsers.length > 0) {
        this.noticeForm.selectedUsers = this.allUsers.map(user => user.studentId);
      }
    },

    handleSelectClear() {
      this.noticeForm.selectedUsers = [];
    },

    async loadTrainingData() {
      try {
        this.trainingSessions = []; // 清空现有数据
        console.log("当前班级ID：", this.classId);
        const res = await selectListByClassId(this.classId);

        // 校验后端数据格式
        if (!Array.isArray(res)) {
          this.$message.error("获取培训数据失败：数据格式错误");
          this.initDefaultTrainingSessions(); // 显示默认结构
          return;
        }

        // 处理分组（空数据时创建默认分组）
        const contentGroups = {};
        if (res.length > 0) {
          res.forEach(item => {
            const contentKey = item.practicalTrainingContent || "未命名培训内容";
            if (!contentGroups[contentKey]) {
              contentGroups[contentKey] = [];
            }
            contentGroups[contentKey].push(item);
          });
        } else {
          contentGroups["默认培训内容"] = []; // 无数据时默认分组
        }

        // 转换为前端结构
        this.trainingSessions = Object.keys(contentGroups).map(content => {
          const arrangeList = contentGroups[content].map(sessionItem => ({
            rawData: sessionItem,
            id: sessionItem.practiceAppointmentId,
            startTime: sessionItem.practiceStartTime || "-",
            endTime: sessionItem.practiceEndTime || "-",
            address: sessionItem.practiceAddress || "-",
            peopleLimit: sessionItem.restrictionNum || 0,
            bookedNum: sessionItem.registrationNum || 0,
            teacher: sessionItem.practicalTeacherName || "-",
            description: sessionItem.remarks || "-"
          }));

          return {
            trainingContent: content,
            arrangeList: arrangeList,
            uploadBtnText: contentGroups[content].length > 0 ? "重新上传" : "上传安排名单", // 动态按钮文本
            operationText: "查看预约名单",
            uploadLoading: false,
            loading: false
          };
        });

        await this.loadStudentsData();

      } catch (error) {
        console.error("加载培训数据失败：", error);
        this.$message.error("加载培训数据失败，请稍后重试");
        this.initDefaultTrainingSessions(); // 报错时显示默认结构
      }
    },

    // 初始化默认培训结构（无数据时调用）
    initDefaultTrainingSessions() {
      this.trainingSessions = [{
        trainingContent: "默认培训内容",
        arrangeList: [],
        uploadBtnText: "上传安排名单",
        operationText: "查看预约名单",
        uploadLoading: false,
        loading: false
      }];
    },

    getPeopleCountProp(session) {
      if (!session.arrangeList || session.arrangeList.length === 0) {
        return '';
      }
      return session.arrangeList[0].bookedNum !== undefined ? 'bookedNum' : 'arrangedNum';
    },

    getPeopleCountLabel(session) {
      if (!session.arrangeList || session.arrangeList.length === 0) {
        return '';
      }
      return session.arrangeList[0].bookedNum !== undefined ? '预约人数' : '安排人数';
    },

    handleStudentNotice() {
      this.noticeDialogVisible = true;
    },

    handleNoticeDialogClose() {
      this.noticeDialogVisible = false;
    },

    submitNotice() {
      this.$refs.noticeForm.validate(async (valid) => {
        if (valid) {
          this.noticeLoading = true;
          try {
            const noticeParams = {
              sendType: this.noticeForm.range === 'all' ? "1" : "2",
              studentIds: this.noticeForm.range === 'all' ? [] : this.noticeForm.selectedUsers,
              isSms: this.noticeForm.sendTypes.includes('0') ? "1" : "0",
              isPortal: this.noticeForm.sendTypes.includes('1') ? "1" : "0",
              isService: this.noticeForm.sendTypes.includes('2') ? "1" : "0",
              noticeContent: this.noticeForm.content,
              sendTime: new Date().toLocaleString('zh-CN', {
                year: 'numeric', month: '2-digit', day: '2-digit',
                hour: '2-digit', minute: '2-digit', second: '2-digit',
                hour12: false
              }).replace(/\//g, '-'),
              trainingClassId: this.classId
            };

            const res = await studentNoticeProcess(noticeParams);

            if (res.code === 200) {
              this.$message.success("通知发送成功");
              this.noticeDialogVisible = false;
            } else {
              this.$message.error("通知发送失败：" + (res.message || "未知错误"));
            }
          } catch (error) {
            console.error("通知发送接口异常：", error);
            this.$message.error("通知发送失败，请稍后重试");
          } finally {
            this.noticeLoading = false;
          }
        } else {
          this.$message.warning('请完善表单信息');
        }
      });
    },

    async queryUsers(query) {
      if (!query) {
        this.userOptions = [...this.allUsers];
        return;
      }

      this.userLoading = true;

      setTimeout(() => {
        try {
          const filteredUsers = this.allUsers.filter(user =>
            user.studentName && user.studentName.includes(query)
          );
          this.userOptions = filteredUsers;
        } catch (error) {
          console.error("搜索学员失败：", error);
          this.userOptions = [];
        } finally {
          this.userLoading = false;
        }
      }, 300);
    },

    async handleViewList(row, text) {
      if (!row.id) {
        this.$message.warning('该时段暂无数据');
        return;
      }

      this.reservationDialogTitle = text;
      this.currentScheduleId = row.id;

      this.reservationInfo = {
        classId: this.classId,
        className: this.className,
        trainingContent: this.trainingSessions.find(s =>
          s.arrangeList.some(a => a.id === row.id)
        )?.trainingContent || '',
        startTime: row.startTime,
        endTime: row.endTime,
        address: row.address,
        peopleLimit: row.peopleLimit
      };

      try {
        const res = await selectClassStudentAppointmentStatus({
          practiceAppointmentId: row.rawData.practiceAppointmentId,
          trainingClassId: this.classId
        });

        this.reservedStudents = (res.appointedStudents || []).map(student => ({
          id: student.studentId,
          name: student.studentName || '-',
          phone: student.phone || '-',
          projectName: student.projectName || '-',
          rawData: student,
          practiceAppointmentId: row.rawData.practiceAppointmentId,
          trainingClassId: this.classId
        }));

        this.unreservedStudents = (res.unappointedStudents || []).map(student => ({
          id: student.studentId,
          name: student.studentName || '-',
          phone: student.phone || '-',
          projectName: student.projectName || '-',
          rawData: student,
          practiceAppointmentId: row.rawData.practiceAppointmentId,
          trainingClassId: this.classId
        }));

        this.selectedReservedStudents = [];
        this.selectedUnreservedStudents = [];
        this.reservationDialogVisible = true;

      } catch (error) {
        console.error("获取预约名单失败：", error);
        this.$message.error("获取预约名单失败，请稍后重试");
      }
    },

    handleReservedSelectionChange(val) {
      this.selectedReservedStudents = val;
    },

    handleUnreservedSelectionChange(val) {
      this.selectedUnreservedStudents = val;
    },

    async batchRemoveReservation() {
      if (this.selectedReservedStudents.length === 0) {
        this.$message.warning("请先选中要移出的预约学员");
        return;
      }

      try {
        const removeIds = this.selectedReservedStudents.map(
          (item) => item.rawData.practiceClassStudentId
        );
        await editAppointmentStatus(removeIds);

        this.unreservedStudents = [
          ...this.unreservedStudents,
          ...this.selectedReservedStudents
        ];
        this.reservedStudents = this.reservedStudents.filter(
          (item) => !removeIds.includes(item.rawData.practiceClassStudentId)
        );

        this.$refs.reservedTable.clearSelection();
        this.selectedReservedStudents = [];
        this.$message.success("批量移出成功");
      } catch (error) {
        console.error("批量移出失败：", error);
        this.$message.error("批量移出失败，请稍后重试");
      }
    },

    async batchAddReservation() {
      if (this.selectedUnreservedStudents.length === 0) {
        this.$message.warning("请先选中要预约的学员");
        return;
      }

      const remainingQuota = this.reservationInfo.peopleLimit - this.reservedStudents.length;
      if (this.selectedUnreservedStudents.length > remainingQuota) {
        this.$message.warning(`剩余可预约名额为${remainingQuota}，请减少选中人数`);
        return;
      }

      try {
        const addList = this.selectedUnreservedStudents.map((item) => ({
          practiceAppointmentId: item.practiceAppointmentId,
          trainingClassId: item.trainingClassId,
          studentId: item.rawData.studentId,
          projectId: item.rawData.projectId,
        }));
        await addPractice(addList);

        this.reservedStudents = [
          ...this.reservedStudents,
          ...this.selectedUnreservedStudents
        ];
        const addedIds = this.selectedUnreservedStudents.map((item) => item.id);
        this.unreservedStudents = this.unreservedStudents.filter(
          (item) => !addedIds.includes(item.id)
        );

        this.$refs.unreservedTable.clearSelection();
        this.selectedUnreservedStudents = [];
        this.$message.success("批量预约成功");
      } catch (error) {
        console.error("批量预约失败：", error);
        this.$message.error("批量预约失败，请稍后重试");
      }
    },

    async handleRemoveReservation(row) {
      try {
        const index = this.reservedStudents.findIndex(item => item.id === row.id);
        if (index !== -1) {
          const removed = this.reservedStudents.splice(index, 1)[0];
          this.unreservedStudents.push(removed);

          await editAppointmentStatus([row.rawData.practiceClassStudentId]);

          this.$refs.reservedTable.clearSelection();
          this.selectedReservedStudents = [];
          this.$message.success("移出成功");
        }
      } catch (error) {
        console.error("移出失败：", error);
        this.$message.error("移出失败，请稍后重试");
      }
    },

    async handleAddReservation(row) {
      if (this.reservationInfo.peopleLimit && this.reservedStudents.length >= this.reservationInfo.peopleLimit) {
        this.$message.warning(`已达最大预约人数(${this.reservationInfo.peopleLimit})`);
        return;
      }

      try {
        const index = this.unreservedStudents.findIndex(item => item.id === row.id);
        if (index !== -1) {
          const added = this.unreservedStudents.splice(index, 1)[0];
          this.reservedStudents.push(added);

          await addPractice([{
            practiceAppointmentId: row.practiceAppointmentId,
            trainingClassId: row.trainingClassId,
            studentId: row.rawData.studentId,
            projectId: row.rawData.projectId
          }]);

          this.$refs.unreservedTable.clearSelection();
          this.selectedUnreservedStudents = [];
          this.$message.success("预约成功");
        }
      } catch (error) {
        console.error("预约失败：", error);
        this.$message.error("预约失败，请稍后重试");
      }
    },

    handleEditSchedule(row, sessionIndex) {
      this.$router.push({
        path: '/training/schedule/edit',
        query: {
          classId: this.classId,
          scheduleId: row.id || '',
          sessionIndex
        }
      });
    },

    handleUploadSuccess(response, sessionIndex) {
      if (response.success) {
        this.$message.success('文件上传成功');
        this.loadTrainingData(); // 上传成功后重新加载数据
      } else {
        this.$message.error('文件上传失败：' + (response.message || '未知错误'));
      }
      this.trainingSessions[sessionIndex].uploadLoading = false;
    },

    handleUploadError() {
      this.$message.error('文件上传失败，请稍后重试');
      this.trainingSessions.forEach(session => {
        session.uploadLoading = false;
      });
    }
  }
};
</script>

<style scoped>
/* 培训班多时段安排样式 */
.training-sessions {
  margin: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.session-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
  flex-wrap: wrap;
}

.session-header .info-item {
  margin-right: 25px;
  margin-bottom: 10px;
  font-weight: 500;
  color: #333;
}

.status-draft {
  color: #666;
}

.status-ongoing {
  color: #409eff;
}

.status-completed {
  color: #67c23a;
}

.session-group {
  margin-bottom: 25px;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
  transition: all 0.3s;
}

.session-group:hover {
  border-color: #ddd;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.session-group-disabled {
  opacity: 0.7;
}

.session-content-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.content-label {
  font-weight: 500;
  margin-right: 8px;
  color: #666;
}

.content-value {
  margin-right: 25px;
  color: #333;
  flex: 1;
  min-width: 200px;
}

.upload-area {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.upload-label {
  margin-right: 8px;
  color: #666;
}

.upload-btn {
  margin-right: 12px;
}

/* 预约名单弹窗样式 */
.reservation-info {
  margin-bottom: 20px;
}

.info-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.info-label {
  font-weight: 500;
  margin-right: 8px;
  color: #666;
  min-width: 80px;
}

.info-value {
  margin-right: 20px;
  margin-bottom: 5px;
  color: #333;
}

.remaining-quota-warning {
  color: #f56c6c;
  font-weight: 500;
}

.students-container {
  display: flex;
  gap: 20px;
}

.students-panel {
  flex: 1;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
}

.panel-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0;
}

.batch-btn {
  color: #409eff;
  padding: 4px 0;
}

.batch-btn:hover {
  color: #66b1ff;
  text-decoration: underline;
}

.batch-btn:disabled {
  color: #c0c4cc;
  cursor: not-allowed;
  text-decoration: none;
}

/* 表格样式优化 */
.el-table {
  font-size: 14px;
  border-radius: 4px;
  overflow: hidden;
}

.el-table__header {
  background-color: #f5f7fa !important;
}

.el-table__header th {
  font-weight: 500 !important;
  color: #303133 !important;
  border-bottom: 1px solid #e6e8eb !important;
}

.el-table__body tr {
  height: 50px !important;
}

.el-table__body td {
  padding: 12px 8px !important;
  color: #606266 !important;
  border-bottom: 1px solid #f0f2f5 !important;
}

.el-table__body tr:hover > td {
  background-color: #f9fafc !important;
}

.el-table__body tr.current-row > td {
  background-color: #eef5ff !important;
  border-left: 2px solid #409eff !important;
}

.el-table--border th,
.el-table--border td {
  border-right: 1px solid #f0f2f5 !important;
}

.el-table--border::after,
.el-table--group::after,
.el-table td.gutter:last-of-type {
  background-color: #f0f2f5 !important;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .session-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .session-header .info-item {
    margin-right: 0;
    width: 100%;
  }

  .session-content-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .content-value {
    margin-right: 0;
    margin-bottom: 10px;
    width: 100%;
  }

  .upload-area {
    width: 100%;
  }

  .students-container {
    flex-direction: column;
  }
}

/* 预约名单弹窗样式优化 */
.reservation-dialog .el-dialog {
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.reservation-dialog .el-dialog__body {
  flex: 1;
  overflow: auto;
  max-height: calc(80vh - 110px);
  padding: 20px;
}

.students-container {
  display: flex;
  gap: 20px;
  height: 500px;
}

.students-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.students-panel .el-table {
  flex: 1;
  overflow: auto;
}

.students-panel .el-table__body-wrapper {
  max-height: 400px;
  overflow-y: auto;
}

/* 学员通知弹窗样式优化 */
.selected-users-form-item {
  margin-bottom: 10px;
}

.selected-count {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  text-align: right;
}

:deep(.el-select-dropdown__item) {
  display: flex;
  justify-content: space-between;
  padding: 8px 20px;
}

:deep(.el-select__tags) {
  max-height: 80px;
  overflow-y: auto;
}

@media (max-width: 768px) {
  .selected-users-form-item {
    margin-bottom: 15px;
  }
}
</style>
